<script setup lang="ts">
import { reactive, ref } from "vue";
import { editUserAPI } from "@/api/user.ts";
import type { FormInstance } from 'element-plus'
import { ElMessage } from "element-plus";

const dialogTableVisible = ref(false)
const ruleFormRef = ref()
const emit = defineEmits(["getUserList"])
const id = ref('')
const editForm = reactive({
  username: '',
  isActive: undefined
})

// 清空表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 初始化
const init = (row: any) => {
  id.value = row._id
  dialogTableVisible.value = true
  editForm.username = row.username
  editForm.isActive = row.isActive
}

// 取消
const handleCancel = () => {
  dialogTableVisible.value = false
  resetForm(ruleFormRef.value)
}

// 确认
const handleCommit = async () => {
  const res: any = await editUserAPI(id.value, editForm)
  res.code === 0 ? ElMessage.success(res.message) : ElMessage.error(res.message)
  emit('getUserList')
  handleCancel()
}

defineExpose({
  init
})
</script>

<template>
  <div>
    <el-dialog v-model="dialogTableVisible" title="编辑用户" width="40%">
      <el-form ref="ruleFormRef"
               :model="editForm">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"/>
        </el-form-item>
        <el-form-item label="活跃状态">
          <el-switch v-model="editForm.isActive"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleCommit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

</style>
